package com.example.taphelper.service

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.content.Intent
import android.graphics.Path
import android.graphics.PixelFormat
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Gravity
import android.view.WindowManager
import android.view.accessibility.AccessibilityEvent
import android.widget.Toast
import com.example.taphelper.utils.TapConfig
import com.example.taphelper.utils.ClickHistoryManager
import kotlin.random.Random
import java.util.UUID

class TapAccessibilityService : AccessibilityService() {
    
    companion object {
        private const val TAG = "TapAccessibilityService"
        var instance: TapAccessibilityService? = null
            private set
    }
    
    private val handler = Handler(Looper.getMainLooper())
    private var clickRunnable: Runnable? = null
    private var currentConfig: TapConfig? = null
    private var isClicking = false
    private var clickCount = 0
    private var currentSessionId = ""
    private lateinit var historyManager: ClickHistoryManager
    
    override fun onServiceConnected() {
        super.onServiceConnected()
        instance = this
        historyManager = ClickHistoryManager(this)
        Log.d(TAG, "无障碍服务已连接")
        Toast.makeText(this, "点击助手服务已启动", Toast.LENGTH_SHORT).show()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        instance = null
        stopClicking()
        Log.d(TAG, "无障碍服务已销毁")
    }
    
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        // 这里可以监听其他应用的事件，暂时不需要处理
    }
    
    override fun onInterrupt() {
        Log.w(TAG, "无障碍服务被中断")
        stopClicking()
    }
    
    /**
     * 开始智能随机化自动点击
     */
    fun startClickingWithDelay(config: TapConfig) {
        if (isClicking) {
            stopClicking()
        }
        
        currentConfig = config
        clickCount = 0
        isClicking = true
        currentSessionId = UUID.randomUUID().toString()
        
        Log.d(TAG, "准备开始智能点击: $config (会话ID: $currentSessionId)")
        
        if (config.delayMillis > 0) {
            // 显示倒计时
            showCountdown(config.delayMillis) {
                startSmartClicking()
            }
        } else {
            startSmartClicking()
        }
    }
    
    /**
     * 显示倒计时
     */
    private fun showCountdown(delayMs: Long, onComplete: () -> Unit) {
        val seconds = (delayMs / 1000).toInt()
        var remaining = seconds
        
        val countdownRunnable = object : Runnable {
            override fun run() {
                if (remaining > 0 && isClicking) {
                    Toast.makeText(this@TapAccessibilityService, 
                        "开始倒计时: $remaining 秒", Toast.LENGTH_SHORT).show()
                    remaining--
                    handler.postDelayed(this, 1000)
                } else if (isClicking) {
                    Toast.makeText(this@TapAccessibilityService, 
                        "智能点击开始！", Toast.LENGTH_SHORT).show()
                    onComplete()
                }
            }
        }
        
        handler.post(countdownRunnable)
    }
    
    /**
     * 开始智能随机化点击
     */
    private fun startSmartClicking() {
        if (!isClicking || currentConfig == null) return
        
        val config = currentConfig!!
        
        // 检查是否需要随机停顿
        if (config.shouldRandomPause()) {
            val pauseTime = config.getRandomPauseTime()
            Log.d(TAG, "智能停顿 ${pauseTime}ms 模拟真人行为")
            
            handler.postDelayed({
                performSmartClick()
            }, pauseTime)
        } else {
            performSmartClick()
        }
    }
    
    /**
     * 执行智能随机化点击
     */
    private fun performSmartClick() {
        if (!isClicking || currentConfig == null) return
        
        val config = currentConfig!!
        
        // 获取随机化的点击位置
        val (randomX, randomY) = config.getRandomizedPosition()
        
        // 执行点击
        performClick(randomX, randomY)
        
        // 记录点击历史
        if (::historyManager.isInitialized) {
            historyManager.addClickRecord(randomX, randomY, currentSessionId)
        }
        
        clickCount++
        Log.d(TAG, "智能点击 #$clickCount: ($randomX, $randomY) [原始: (${config.x}, ${config.y})]")
        
        // 安排下一次点击，使用随机化的时间间隔
        val nextInterval = config.getRandomizedInterval()
        
        clickRunnable = Runnable {
            if (isClicking) {
                startSmartClicking()
            }
        }
        
        handler.postDelayed(clickRunnable!!, nextInterval)
        Log.d(TAG, "下次点击延迟: ${nextInterval}ms")
    }
    
    /**
     * 执行单次点击
     */
    private fun performClick(x: Int, y: Int): Boolean {
        try {
            val path = Path()
            path.moveTo(x.toFloat(), y.toFloat())
            
            val gestureBuilder = GestureDescription.Builder()
            gestureBuilder.addStroke(GestureDescription.StrokeDescription(path, 0, 50))
            
            val gestureDescription = gestureBuilder.build()
            
            val result = dispatchGesture(gestureDescription, object : GestureResultCallback() {
                override fun onCompleted(gestureDescription: GestureDescription?) {
                    super.onCompleted(gestureDescription)
                    Log.d(TAG, "点击执行成功: ($x, $y)")
                }
                
                override fun onCancelled(gestureDescription: GestureDescription?) {
                    super.onCancelled(gestureDescription)
                    Log.w(TAG, "点击被取消: ($x, $y)")
                }
            }, null)
            
            return result
        } catch (e: Exception) {
            Log.e(TAG, "点击执行失败: ($x, $y)", e)
            return false
        }
    }
    
    /**
     * 停止自动点击
     */
    fun stopClicking() {
        isClicking = false
        clickRunnable?.let { 
            handler.removeCallbacks(it)
            clickRunnable = null
        }
        currentConfig = null
        clickCount = 0
        Log.d(TAG, "智能点击已停止")
    }
    
    /**
     * 获取当前状态
     */
    fun isCurrentlyClicking(): Boolean = isClicking
    
    fun getCurrentConfig(): TapConfig? = currentConfig
    
    fun getClickCount(): Int = clickCount
} 